/* eslint-disable max-len */
import T from 'ant-design-vue/es/table/Table'
import get from 'lodash.get'
import i18n from '@/lang'
import tableDraggable from '@/utils/tableDraggable'
import { minxinGetDomHeight2, minxinWindowSizeEvent } from '@/utils/mixin'
import tbColAliginMixin from '@/utils/tbColAliginMixin'
const orderType = {
  ascend: 'ASC',
  descend: 'DESC'
}
export default {
  mixins: [minxinGetDomHeight2, minxinWindowSizeEvent, tbColAliginMixin],
  props: Object.assign({}, T.props, {
    rowKey: {
      type: [String, Function],
      default: 'id'
    },
    data: {
      type: [Function, Array],
      required: false
    },
    pageNum: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 20
    },
    pageSizeOptions: {
      type: Array,
      default: () => ['10', '15', '50', '100']
    },
    showSizeChanger: {
      type: Boolean,
      default: true
    },
    size: {
      type: String,
      default: 'default'
    },
    // 表格的底部
    hasFooter: {
      type: Boolean,
      default: false
    },
    /**
     * {
     *   show: true,
     *   clear: Function
     * }
     */
    alert: {
      type: [Object, Boolean],
      default: null
    },
    rowSelection: {
      type: Object,
      default: null
    },
    /** @Deprecated */
    showAlertInfo: {
      type: Boolean,
      default: false
    },
    showPagination: {
      type: String | Boolean,
      default: true
    },
    dataSource: {
      type: Array,
      default () {
        return []
      }
    },
    loading: {
      type: Boolean,
      default: false
    },
    // .ant-table-body最小高度
    minHeight: {
      type: Number,
      // 两行高度
      default: 76
    },
    // 是否需要表格垂直滚动条
    scrollY: {
      type: Number,
      default: 1
    },
    scrollX: {
      type: Number,
      default: 0
    },
    /**
     * 用于计算表格自适应高度的容器 class
     */
    wrapRef: {
      type: String,
      default: 'pageViewSty'
    },
  }),
  data () {
    return {
      needTotalList: [],
      selectedRows: [],
      selectedRowKeys: [],
      localLoading: false,
      localDataSource: [],
      localPagination: Object.assign({}, T.props.pagination),
      resizeFuns: ['calcContentHeight'],
      targetRef: 'ant-table-body'
    }
  },

  watch: {
    // eslint-disable-next-line no-unused-vars
    'localPagination.current' (val) {
      this.getPagination()
    },
    // eslint-disable-next-line no-unused-vars
    localDataSource (val) {
      this.$nextTick(() => {
        this.calcContentHeight()
      })
    },
    pageNum (val) {
      Object.assign(this.localPagination, {
        current: val
      })
      this.getPagination()
    },
    pageSize (val) {
      Object.assign(this.localPagination, {
        pageSize: val
      })
      this.getPagination()
    },
    showSizeChanger (val) {
      Object.assign(this.localPagination, {
        showSizeChanger: val
      })
      this.getPagination()
    },
    // 直接传递数据的时候，此时不用data属性
    dataSource: {
      handler (val) {
        if (!this.data) {
          this.localDataSource = val
        }
      },
      immediate: true
    },
    loading: {
      handler (val) {
        this.localLoading = val
      },
      immediate: true
    }
  },
  created () {
    if (!this.data) {
      return
    }
    this.localPagination = ['auto', true].includes(this.showPagination) && Object.assign({}, this.localPagination, {
      current: this.pageNum,
      pageSize: this.pageSize,
      pageSizeOptions: this.pageSizeOptions,
      showSizeChanger: this.showSizeChanger,
      size: 'small',
      showQuickJumper: true,
      showTotal: total => `Total ${total} items`
    })
    this.needTotalList = this.initTotalList(this.columns)
    this.loadData()
    this.getPagination()
  },
  methods: {
    // 获取table的分页情况
    getPagination () {
      this.$emit('getPagination', this.localPagination)
    },
    /**
     * 表格重新加载方法
     * 如果参数为 true, 则强制刷新到第一页
     * @param Boolean bool
     */
    refresh (bool = false) {
      bool && (this.localPagination = Object.assign({}, {
        current: 1, pageSize: this.pageSize
      }))
      this.loadData()
    },
    /**
     * 加载数据方法
     * @param {Object} pagination 分页选项器
     * @param {Object} filters 过滤条件
     * @param {Object} sorter 排序条件
     */
    loadData (pagination, filters, sorter) {
      this.localDataSource = []
      if ((!sorter || !sorter.order) && this.order) {
        // eslint-disable-next-line no-param-reassign
        sorter = this.order
      }
      const parameter = Object.assign({
        pageNo: (pagination && pagination.current) ||
            this.localPagination.current || this.pageNum,
        pageSize: (pagination && pagination.pageSize) ||
            this.localPagination.pageSize || this.pageSize
      }, {
        ...filters
      }
      )
      if (sorter && sorter.columnKey) {
        if (sorter.order) {
          parameter.order = `${sorter.columnKey},${orderType[sorter.order]}`
        } else {
          parameter.order = undefined
        }
      }
      const result = this.data(parameter)
      // 对接自己的通用数据接口需要修改下方代码中的 r.pageNo, r.totalPage, r.data
      // eslint-disable-next-line
      if ((typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function') {
        this.localLoading = true
        result.then(r => {
          if (r) {
            this.localPagination = Object.assign({}, this.localPagination, {
              current: r.pageNo || this.localPagination.current || 1, // 返回结果中的当前分页数
              total: r.totalCount || r.data.length, // 返回结果中的总记录数
              showSizeChanger: this.showSizeChanger,
              pageSize: (pagination && pagination.pageSize) ||
              this.localPagination.pageSize
            })
            // 如果请求的当前页没有数据 自动跳到有数据的最后一页
            if (Array.isArray(r.data) && r.data.length === 0 && this.localPagination.current !== 1 && this.localPagination.current > r.totalPage) {
              this.localPagination.current = r.totalPage
              this.loadData()
              return
            }

            // 这里用于判断接口是否有返回 r.totalPage 或 this.showPagination = false
            // 当情况满足时，表示数据不满足分页大小，关闭 table 分页功能

            // eslint-disable-next-line no-mixed-operators
            (!this.showPagination || !r.totalRow && this.showPagination === 'auto') && (this.localPagination = false)
            this.localDataSource = r.data.length ? r.data : [] // 返回结果中的数组数据
          }
          this.localLoading = false
        }).finally(() => {
          this.localLoading = false
        })
      }
    },
    handleTableChange (pagination, filters, sorter) {
      this.order = sorter
      this.loadData(pagination, filters, sorter)
    },
    initTotalList (columns) {
      const totalList = []
      columns && columns instanceof Array && columns.forEach(column => {
        if (column.needTotal) {
          totalList.push({
            ...column,
            total: 0
          })
        }
      })
      return totalList
    },
    /**
     * 用于更新已选中的列表数据 total 统计
     * @param selectedRowKeys
     * @param selectedRows
     */
    updateSelect (selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
      const list = this.needTotalList
      this.needTotalList = list.map(item => {
        return {
          ...item,
          total: selectedRows.reduce((sum, val) => {
            // eslint-disable-next-line radix
            const total = sum + parseInt(get(val, item.dataIndex))
            return isNaN(total) ? 0 : total
          }, 0)
        }
      })
    },
    /**
     * 清空 table 已选中项
     */
    clearSelected () {
      if (this.rowSelection) {
        this.rowSelection.onChange([], [])
        this.updateSelect([], [])
      }
    },
    /**
     * 处理交给 table 使用者去处理 clear 事件时，内部选中统计同时调用
     * @param callback
     * @returns {*}
     */
    renderClear (callback) {
      if (this.selectedRowKeys.length <= 0) return null
      return (
        <a style="margin-left: 24px" onClick={() => {
          this.clearSelected()
          callback()
        }}>{i18n.t('clear')}</a>
      )
    },
    renderAlert () {
      // 绘制统计列数据
      const needTotalItems = this.needTotalList.map((item) => {
        return (<span style="margin-right: 12px">
          {item.title}总计 <a style="font-weight: 600">{!item.customRender ? item.total : item.customRender(item.total)}</a>
        </span>)
      })

      // 绘制 清空 按钮
      // eslint-disable-next-line no-nested-ternary
      const clearItem = (typeof this.alert.clear === 'boolean' && this.alert.clear) ? (
        this.renderClear(this.clearSelected)
      ) : (this.alert !== null && typeof this.alert.clear === 'function') ? (
        this.renderClear(this.alert.clear)
      ) : null

      // 绘制 alert 组件
      return (
        <a-alert showIcon={true} style="margin-bottom: 16px">
          <template slot="message">
            <span style="margin-right: 12px">{this.$t('selected')} <a style="font-weight: 600">{this.selectedRowKeys.length} {this.$t('item')}</a></span>
            {needTotalItems}
            {clearItem}
          </template>
        </a-alert>
      )
    },
    // eslint-disable-next-line no-unused-vars
    changePageSize (page, pageSize) {
      this.localPagination.current = page
      this.loadData()
    },
    showSizeChange (current, size) {
      this.localPagination.pageSize = size
      this.loadData()
    },
    showTotal (total) {
      return i18n.t('recordTotalDesc').replace('__COUNT__', total)
    },
    getTBodyContentMaxHeight () {
      const pageViewDom = document.querySelector('.pageViewSty')
      const tableListPageTopDom = document.querySelector('.tableListPageTop')
      const withTableAndPaginationDom = document.querySelector('.withTableAndPaginationWrap')
      const outerHeight = withTableAndPaginationDom.offsetHeight
      let paginationHeight = 0
      if (this.showPagination && this.localPagination.total) {
        const paginationWrapperDom = withTableAndPaginationDom.querySelector('.pagination-wrapper')
        if (paginationWrapperDom) {
          paginationHeight = paginationWrapperDom.offsetHeight
        }
        const style = window.getComputedStyle(paginationWrapperDom, null)
        const marginT = parseFloat(style.getPropertyValue('margin-top'))
        const marginB = parseFloat(style.getPropertyValue('margin-bottom'))
        paginationHeight = paginationHeight + marginT + marginB
      }

      console.log('dom1', pageViewDom.offsetHeight - tableListPageTopDom.offsetHeight - paginationHeight - 48, paginationHeight, outerHeight, paginationHeight, this.showPagination, this.localPagination.total)
    }
  },
  mounted () {
  },
  render () {
    const props = {}
    const localKeys = Object.keys(this.$data)
    // eslint-disable-next-line no-mixed-operators
    const showAlert = (typeof this.alert === 'object' && this.alert !== null && this.alert.show) && typeof this.rowSelection.selectedRowKeys !== 'undefined' || this.alert

    Object.keys(T.props).forEach(k => {
      const localKey = `local${k.substring(0, 1).toUpperCase()}${k.substring(1)}`
      if (localKeys.includes(localKey)) {
        props[k] = this[localKey]
        return props[k]
      }
      if (k === 'rowSelection') {
        if (showAlert && this.rowSelection) {
          // 如果需要使用alert，则重新绑定 rowSelection 事件
          // 如果不用判断checkbox是否可选 则需要默认原始
          // eslint-disable-next-line no-unused-vars
          const defautCheckboxProps = record => ({
            props: {}
          })
          props[k] = {
            selectedRows: this.selectedRows,
            selectedRowKeys: this.selectedRowKeys,
            type: this.rowSelection.type || 'checkbox',
            onChange: (selectedRowKeys, selectedRows) => {
              this.updateSelect(selectedRowKeys, selectedRows)
              typeof this[k].onChange !== 'undefined' && this[k].onChange(selectedRowKeys, selectedRows)
            },
            getCheckboxProps: this.rowSelection.getCheckboxProps || defautCheckboxProps // 控制checkbox是否可选
          }
          return props[k]
        // eslint-disable-next-line no-else-return
        } else if (!this.rowSelection) {
          // 如果没打算开启 rowSelection 则清空默认的选择项
          props[k] = null
          return props[k]
        }
      }
      props[k] = this[k]
      return props[k]
    })
    const hasShowPagination = this.showPagination && this.localPagination.total
   // tableDraggable(props.columns)
   if(this.draggable !== false){
    props.components = tableDraggable(props.columns)
  }
    props.scroll = { x: 0 }
    if (this.scrollY) {
      props.scroll.y = this.contentHeight < this.scrollY ? this.scrollY : this.contentHeight
    }
    if (this.scrollX) {
      props.scroll.x = this.scrollX
    }
    props.pagination = false
    props.locale = {
      emptyText: ''
    }
    const table = (
      <a-table {...{ props, scopedSlots: { ...this.$scopedSlots } }} onChange={this.handleTableChange}>
        { Object.keys(this.$slots).map(name => (<template slot={name}>{this.$slots[name]}</template>)) }
      </a-table>
    )
    const pagination = (<a-pagination pageSizeOptions={['10', '20', '50', '100']} pageSize={this.localPagination.pageSize}
      total={this.localPagination.total} current={this.localPagination.current} onChange={this.changePageSize}
      onShowSizeChange={this.showSizeChange} showTotal={this.showTotal}
      showQuickJumper showSizeChanger size="small"/>)
    return (
      <div class="dsxw-table-pagination-wrapper commonTableSty" style="min-height:200px">
        <div class="table-wrapper" ref="tableWrapperRef">
          {showAlert ? this.renderAlert() : null}
          {table}
        </div>
        {hasShowPagination ? <div class="pagination-wrapper">{pagination}</div> : ''}
      </div>
      // <div class="withTableAndPaginationWrap">
      //   <div class="commonTableWrap">
      //     { showAlert ? this.renderAlert() : null }
      //     { table }
      //   </div>
      //   {hasShowPagination ? (<div class='pagination-wrapper'>
      //     {pagination}
      //   </div>) : ''}
      // </div>
    )
  }
}
